import { Get, Inject, Injectable } from '@nestjs/common';
import * as Minio from 'minio';
// import { MINIO_CLIENT } from './minio.module';

export const MINIO_CLIENT = 'MINIO_CLIENT';

const MINI_PORT = 6002;
@Injectable()
export class MinioService {
  @Inject(MINIO_CLIENT)
  private readonly minioClient: Minio.Client;

  async uploadFile(
    bucketName: string,
    objectName: string,
    fileBuffer: Buffer,
    fileSize: number,
    metaData: Minio.ItemBucketMetadata,
  ): Promise<string> {
    try {
      await this.minioClient.putObject(
        bucketName,
        objectName,
        fileBuffer,
        fileSize,
        metaData,
      );
      return `http://localhost:${MINI_PORT}/${bucketName}/${objectName}`;
    } catch (error) {
      console.log('object upload failed:', error);
      throw new Error('object upload failed');
    }
  }

  async test() {
    try {
      await this.minioClient.fPutObject(
        'xf-bucket',
        'test.json',
        './package.json',
      );
      return 'http://localhost:${MINI_PORT}/xf-bucket/test.json';
    } catch (error) {
      console.log('object upload failed:', error);
      return 'object upload failed';
    }
  }

  async presignedUrl(name: string) {
    try {
      const url = await this.minioClient.presignedPutObject(
        'xf-bucket',
        name,
        24 * 60 * 60,
      );
      return url;
    } catch (error) {
      console.log('presignedUrl failed:', error);
      return 'presignedUrl failed';
    }
  }
}
